import WeCropper from './we-cropper.js';

const device = wx.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight - 50;
const app = getApp();
Page({
  _isCropper: true,
  data: {
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300,
      },
    },
    showPreview: false,
    cuttedImg: '',
    uploadUrl: '',
    sceneName: '',
    src: '',
    isCropper: true,
  },

  touchStart(e) {
    this.cropper.touchStart(e);
  },
  touchMove(e) {
    this.cropper.touchMove(e);
  },
  touchEnd(e) {
    this.cropper.touchEnd(e);
  },

  // 生成裁剪后的图片，存入缓存，可以直接上传。
  getCropperImage() {
    let that = this;
    let { isCropper } = this.data;
    if (isCropper && this._isCropper) {
      this.setData({ isCropper: false });
      this._isCropper = false;
      this.cropper.getCropperImage(function(src) {
        if (src) {
          const uploadUrl = wx.getStorageSync('uploadUrl');

          if (that.data.sceneName === 'card') {
            wx.showLoading({
              title: '上传中...',
              mask: true,
            });
            wx.uploadFile({
              url: uploadUrl,
              filePath: src,
              name: 'file',
              formData: app.modules === 'ws_micro_shop' ? { _acid: app.siteInfo.acid, _uniacid: app.siteInfo.uniacid } : {},
              header: app.modules === 'ws_micor_shop' ? { 'Content-Type': 'multipart/form-data' } : {},
              success: function(res) {
                let data = JSON.parse(res.data);
                wx.hideLoading();
                if (res.statusCode === 200 && !data.error && data.url) {
                  wx.setStorageSync('resPic', data.url);
                  if (that.data.usetype) {
                    wx.setStorageSync('usetype', that.data.usetype);
                  }
                  wx.setStorageSync('cuttedImg', src);
                  wx.navigateBack({
                    delta: 1,
                  });
                }
                if (!data.url) {
                  wx.showToast({
                    title: data.error.message,
                    icon: 'none',
                  });
                }
              },
              fail: function (res) {
                wx.hideLoading();
                wx.showToast({
                  title: '上传失败 请重试',
                  icon: 'none',
                  duration: 800,
                  success: () => {
                    wx.navigateBack({
                      delta: 1,
                    });
                  },
                });
              },
              complete: function (res) {
                that.setData({ isCropper: true });
                that._isCropper = true;
              },
            });
          } else {
            wx.uploadFile({
              url: uploadUrl,
              filePath: src,
              name: 'file',
              formData: app.modules === 'ws_micro_shop' ? { _acid: app.siteInfo.acid, _uniacid: app.siteInfo.uniacid } : {},
              header: app.modules === 'ws_micro_shop' ? { 'Content-Type': 'multipart/form-data' } : {},
              success: (res) => {
                let data = JSON.parse(res.data);
                if (res.statusCode === 200 && !data.error && data.url) {
                  wx.setStorageSync('resPic', res.data);
                  if (that.data.usetype) {
                    wx.setStorageSync('usetype', that.data.usetype);
                  }
                  wx.setStorageSync('cuttedImg', src);
                  wx.showToast({
                    title: '上传成功',
                    duration: 800,
                    success: () => {
                      wx.navigateBack({
                        delta: 1,
                      });
                    },
                  });
                } else {
                  wx.showToast({
                    title: data.error.message,
                    icon: 'none',
                  });
                }
              },
              complete: function (res) {
                that.setData({ isCropper: true });
                that._isCropper = true;
              },
            });
          }
          that.setData({ src: '' });
        } else {
          that.setData({ isCropper: true });
          that._isCropper = true;
          wx.showToast({
            title: '获取图片地址失败，请重试',
            icon: 'none',
          });
        }
      });
    }
  },

  // 实例化裁剪插件，按sceneName值选择不同的裁剪框尺寸。
  onLoad(option) {
    let { sceneName, src } = option;
    let usetype = option.usetype || '';//兼容同一页面多次引用
    this.setData({
      sceneName,
      src,
      usetype,
    });

    const cropperOptA = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 400) / 2,
        y: (height - 120) / 2,
        width: 400,
        height: 120,
      },
    };
    const cropperOptB = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 80) / 2,
        y: (height - 300) / 2,
        width: 80,
        height: 300,
      },
    };

    // 近似16:9的图片，给通用名片使用
    const cropperOptC = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 345) / 2,
        y: (height - 325) / 2,
        width: 345,
        height: 325,
      },
    };

    //3:2
    const cropperOptD = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 200) / 2,
        width: 300,
        height: 200,
      },
    };

    const cropperOptE = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 375) / 2,
        y: (height - 450) / 2,
        width: 375,
        height: 450,
      },
    };

    // 7:3
    const cropperOptF = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 350) / 2,
        y: (height - 150) / 2,
        width: 350,
        height: 150,
      },
    };

    const cropperOptG = {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 375) / 2,
        y: (height - 180) / 2,
        width: 375,
        height: 180,
      },
    };

    let cropperOpt = null;
    if (sceneName === 'square') {
      cropperOpt = this.data.cropperOpt;
    } else if (sceneName === 'banner') {
      cropperOpt = cropperOptA;
    } else if (sceneName === 'vertical') {
      cropperOpt = cropperOptB;
    } else if (sceneName === 'card') {
      cropperOpt = cropperOptC;
    } else if (sceneName === 'thumb') {
      cropperOpt = cropperOptD;
    } else if (sceneName === 'poster') {
      cropperOpt = cropperOptE;
    } else if (sceneName === 'cover') {
      cropperOpt = cropperOptF;
    } else if (sceneName === 'newbanner') {
      cropperOpt = cropperOptG;
    } else {
      cropperOpt = this.data.cropperOpt;
    }

    this.cropper = new WeCropper(cropperOpt)
      .on('ready', (ctx) => {

      })
      .on('beforeImageLoad', (ctx) => {

        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000,
        });
      })
      .on('imageLoad', (ctx) => {

        wx.hideToast();
      })
      .on('beforeDraw', (ctx, instance) => {

      })
      .updateCanvas();
  },

  // 将选择的图片置入canvas。
  onShow() {
    let src = this.data.src;
    src && this.cropper.pushOrign(src);
  },
});
